package org.cy.shixun.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Map;

//生成token的工具类
@Component
public class JWTUtil {
    //密匙（不要透露出去）
    private static final String secret = "*&hbd)!_";
    //payload就是载荷，用来存放客户的一些信息
    public static String getToken(Map<String,String> payload) {
        JWTCreator.Builder builder = JWT.create();
        //解析载荷
        //["act":"amdin","name":"dddd"]
        for(String k : payload.keySet()) {
            String v = payload.get(k);
            //将map中的数据加载到JWT中
            builder.withClaim(k,v);
        }
        //设置3天以后过去
        //获取当前日期
        Calendar exp = Calendar.getInstance();
        exp.add(Calendar.DATE,3);
        builder.withExpiresAt(exp.getTime());
        //生成token
        //MD5
        //Algorithm.HMAC256加密算法
        String token = builder.sign(Algorithm.HMAC256(secret));
        return token;
    }

//    public static void main(String[] args) {
//        Map<String,String> payload = new HashMap<>();
//        payload.put("account","admin");
//        payload.put("gender","男");
//        //利用载荷生成token
//        String token = JWTUtil.getToken(payload);
//        System.out.println(token);
//    }
}
